package fi.internetix.ck;

import java.util.HashMap;
import org.w3c.dom.Node;

public class NodePrinterUtils {
  
  public static String extractLowercaseTagName(String s) {
    int i = s.lastIndexOf(':');
    return i == -1 ? s.toLowerCase() : s.substring(i + 1).toLowerCase();
  }
  
  public static NodePrinter getNodePrinter(Node node) {
    String nodeName = extractLowercaseTagName(node.getNodeName());
    NodePrinter nodePrinter = nodePrinters.get(nodeName);
    if (nodePrinter == null) {
      nodePrinter = defaultNodePrinter;
    }
    return nodePrinter;
  }

  public static String trim(String str) {
    String s = str == null ? "" : str.trim();
    int i = 0;
    int j = s.length() - 1;
    while (i < s.length() && s.charAt(i) == '\u00A0') {
      i++;
    }
    while (j > 0 && s.charAt(j) == '\u00A0') {
      j--;
    }
    return i == 0 && j == s.length() - 1 ? s.trim() : s.substring(i, j + 1).trim();
  }


  private static final HashMap<String, NodePrinter> nodePrinters = new HashMap<String, NodePrinter>();
  private static final NodePrinter defaultNodePrinter = new HTMLNodePrinter();

  static {
    nodePrinters.put("#text", new TextNodePrinter());
    nodePrinters.put("a", new ANodePrinter());
    nodePrinters.put("applet", new GenericStripNodePrinter(false));
    nodePrinters.put("body", new GenericStripNodePrinter(true));
    nodePrinters.put("div", new GenericContainerNodePrinter());
    nodePrinters.put("embed", new GenericStripNodePrinter(false));
    nodePrinters.put("form", new GenericStripNodePrinter(true));
    nodePrinters.put("frameset", new GenericStripNodePrinter(false));
    nodePrinters.put("h1", new GenericContainerNodePrinter());
    nodePrinters.put("h2", new GenericContainerNodePrinter());
    nodePrinters.put("h3", new GenericContainerNodePrinter());
    nodePrinters.put("h4", new GenericContainerNodePrinter());
    nodePrinters.put("h5", new GenericContainerNodePrinter());
    nodePrinters.put("h6", new GenericContainerNodePrinter());
    nodePrinters.put("head", new GenericStripNodePrinter(false));
    nodePrinters.put("html", new GenericStripNodePrinter(true));
    nodePrinters.put("iframe", new GenericStripNodePrinter(false));
    nodePrinters.put("input", new InputNodePrinter());
    nodePrinters.put("noscript", new GenericStripNodePrinter(false));
    nodePrinters.put("object", new GenericStripNodePrinter(false));
    nodePrinters.put("p", new GenericContainerNodePrinter());
    nodePrinters.put("script", new GenericStripNodePrinter(false));
    nodePrinters.put("span", new GenericContainerNodePrinter());
    nodePrinters.put("style", new GenericStripNodePrinter(false));
    nodePrinters.put("textarea", new TextareaNodePrinter());
  }

}
